/**
 * @author luguoxiang
 * @Date: 2024/02/21 16:55
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */

import { ref } from 'vue';

/**
 * 锚点属性
 */
export interface AnchorProps {
  /**
   * 锚点类名（用于选择所有锚点）
   */
  className: string;

  /**
   * 锚点名称所在属性（默认读取 innerText）
   */
  nameAttr?: string;
}

/**
 * 使用锚点功能
 * @param options
 */
export function useAnchor(options: string | AnchorProps) {
  if (typeof options === 'string') {
    options = { className: options };
  }
  const { className, nameAttr } = options ?? {};

  const anchors = ref<any>([]);
  const currentAnchor = ref('');
  let scrollbar = {};
  let scrollTopFlag = false;

  const getName = nameAttr ? (e: HTMLElement) => e.getAttribute(nameAttr) : (e: HTMLElement) => e.innerText;

  function toAnchor(anchorId: string) {
    scrollTopFlag = true;
    currentAnchor.value = anchorId;
    const el = document.getElementById(anchorId);
    // @ts-ignore
    scrollbar.scrollTo?.(0, el.offsetTop - el.offsetHeight);
  }

  function onScroll(e: any) {
    if (scrollTopFlag) {
      scrollTopFlag = false;
      return;
    }
    e = e.target.scrollTop;
    for (const x of anchors.value) {
      // @ts-ignore
      if (document.getElementById(x.id).offsetTop >= e) {
        currentAnchor.value = x.id;
        break;
      }
    }
  }

  function scrollbarRef(e: any) {
    scrollbar = e;
    const nodes = e.querySelectorAll(`.${className}`);
    anchors.value = [];
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      node.id = className + i;
      anchors.value.push({ name: getName(node), id: node.id });
    }
    currentAnchor.value = nodes[0].id;
  }

  return {
    anchors,
    currentAnchor,
    toAnchor,
    onScroll,
    scrollbarRef,
  };
}
